package com.woorigil.social.domain.qna.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import com.woorigil.social.HtmlUtils;
import com.woorigil.social.HttpUtils;
import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.qna.Qna;
import com.woorigil.social.domain.qna.QnaBox;

@Component (value = "wemakepriceQnaParser")
public class WemakepriceQnaParser implements QnaParser {
	@Override
	public ProviderCode getProviderCode() {
		return ProviderCode.WM;
	}
	
	@Override
	public List<QnaBox> parse(String qnaUrl) {
		List<QnaBox> qnaBoxList = new ArrayList<QnaBox>();

		try {
			String data = HttpUtils.execute(qnaUrl, 1000);
			
			String html = new JSONObject(data).getString("article");
			Document doc = Jsoup.parse(html);
			Element root = doc.select(".sec_cmt ul").first();
			
			QnaBox qnaBox = new QnaBox(null);
			int count = 0;
			for (Element qnaBoxElement : root.children()) {
				if (count > 3) {
					break;
				}
				count++;

				Elements elements = qnaBoxElement.select("dl");
				for (int i=0; i<elements.size(); i++) {
					Element element = elements.get(i);
					Element qnaElement = element.select("dt").get(0);
					if (i == 0) {
						String qUser = "질문자";
						String qDate = qnaElement.select(".date").text();
						String qContent = HtmlUtils.br2nl(element.select(".cmt").get(0).html());
//						System.out.println(qUser + "/" + qDate + "/" + qContent);
						qnaBox = new QnaBox(new Qna(qUser, qDate, qContent));
					} else {
						String aUser = qnaElement.select("strong").text();
						String aDate = qnaElement.select(".date").text();
						String aContent = HtmlUtils.br2nl(element.select(".cmt").get(0).html());
//						System.out.println(aUser + "/" + aDate + "/" + aContent);
						qnaBox.addAnswer(new Qna(aUser, aDate, aContent));
					}
				}
				qnaBoxList.add(qnaBox);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return qnaBoxList;
	}
}
